use crate::errors::{MyError, MyResult};
use crate::utils::common::{path_join, pwd};
use lazy_static::lazy_static;
use regex::Regex;
use std::fs::OpenOptions;
use std::io::Write;
use std::process::Command;

pub fn get_default_git_project_name(git: &str) -> MyResult<String> {
    lazy_static! {
        static ref RE: Regex = Regex::new(r"/([^/]+)\.git$").unwrap();
    }
    if let Some(captures) = RE.captures(git) {
        if let Some(name) = captures.get(1) {
            return Ok(name.as_str().to_owned());
        }
    }
    Err(MyError::custom(&format!(
        "get_default_git_project_name,无效git:{}",
        git
    )))
}
pub fn clone(git: &str, tag: &str, target_path: Option<&str>) -> MyResult<()> {
    let mut args: Vec<String> = vec![
        "clone".to_string(),
        "-b".to_string(),
        tag.to_owned(),
        git.to_owned(),
    ];
    if target_path.is_some() {
        args.push(path_join(&pwd()?, target_path.unwrap())?);
    }
    let _ = Command::new("git")
        .args(args.as_slice())
        .stdout(std::process::Stdio::inherit())
        .output()?;
    Ok(())
}

pub fn append_ignore(project_path: &str, git_name: &str) -> MyResult<()> {
    let ignore_file = path_join(&pwd()?, &path_join(project_path, ".gitignore")?)?;
    let mut file = OpenOptions::new()
        .create(true)
        .append(true)
        .open(ignore_file)?;

    writeln!(file, "{}", git_name)?;
    Ok(())
}
